package com.coollang.smartbra.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.coollang.smartbra.R;
import com.coollang.smartbra.activity.LoginActivity;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.interfaces.TextChangeListener;
import com.coollang.smartbra.interfaces.view.LoginView;
import com.coollang.smartbra.presenter2.LoinPresenter;
import com.coollang.smartbra.presenter2.impl.LoinPresenterImpl;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.StringUtils;
import com.coollang.smartbra.utils.ToastUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.coollang.smartbra.utils.Urls;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 登录页面的Fragment
 */

public class LoginFragment extends LoginBaseFragment implements View.OnClickListener, LoginView {

    @BindView(R.id.rv_login)
    FrameLayout rvLogin;
    private View view;
    private Context mContext;
    @BindView(R.id.et_phone)
    EditText etPhoneLogin;
    @BindView(R.id.et_pass)
    EditText etPassLogin;
    @BindView(R.id.iv_clear_phone)
    ImageView ivClearLogin;
    @BindView(R.id.iv_see_pass)
    ImageView ivSeePass;
    @BindView(R.id.tv_regist)
    TextView tvRigst;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    String phone;
    String pass;
    private LoinPresenter mLoinPresenter;

    @Override
    protected View inflateView(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.item_login, null, false);
        return view;
    }

    @Override
    protected void initView(View view) {
        ButterKnife.bind(this, view);
        mContext = this.getActivity();
        initListener();
    }

    private void initListener() {
        rvLogin.setOnClickListener(this);
        UIUtils.setLengthFilter(etPhoneLogin, 11);
        UIUtils.setLengthFilter(etPassLogin, 20);
        ivClearLogin.setOnClickListener(this);
        ivSeePass.setOnClickListener(this);
        tvRigst.setOnClickListener(this);
        tvForget.setOnClickListener(this);

        // 对手机号输入框做监听
        listenerPhoneEdit();

        // 对手机密码输入框做监听
        listenerPassWEdit();
    }

    private void listenerPhoneEdit() {
        etPhoneLogin.addTextChangedListener(new TextChangeListener() {
            @Override
            public void onTextChange(String str) {
                if (str.length() == 0) {
                    ivClearLogin.setVisibility(View.GONE);
                } else {
                    ivClearLogin.setVisibility(View.VISIBLE);
                }

                if (str.length() == 1) {
                    int anInt = Integer.parseInt(str.subSequence(0, 1).toString());
                    if (anInt != 1) {
                        etPhoneLogin.setText("");
                    }
                }
            }
        });
    }

    private void listenerPassWEdit() {
        etPassLogin.addTextChangedListener(new TextChangeListener() {
            @Override
            public void onTextChange(String str) {
                if (str.length() == 0) {
                    ivSeePass.setVisibility(View.GONE);
                } else {
                    ivSeePass.setVisibility(View.VISIBLE);
                }

                if (str.contains(" ")) {
                    str = str.trim();
                    etPassLogin.setText(str.trim());
                    etPassLogin.setSelection(str.length());
                }
            }
        });

    }

    @Override
    protected void initData() {
        mLoinPresenter = new LoinPresenterImpl(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.iv_clear_phone:
                etPhoneLogin.setText("");
                ivClearLogin.setVisibility(View.GONE);
                break;
            case R.id.iv_see_pass:
                UIUtils.seePassword(etPassLogin, ivSeePass);
                break;
            case R.id.tv_regist:
                ((LoginActivity) mContext).goToRegistView();
                break;
            case R.id.tv_forget:
                ((LoginActivity) mContext).goToChangePassView();
                break;
            case R.id.rv_login:
                if (MyApplication.getApplication().hasNet()) {
                    doLogin();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 登录
     */
    private void doLogin() {
        phone = etPhoneLogin.getText().toString();
        pass = etPassLogin.getText().toString();

        if (!chekLogin()) {
            return;
        }

        if (phone.length() == 0 || !StringUtils.matchPhone(phone) || pass.length() == 0 || pass.length() < 6) {
            ToastUtils.showToast(UIUtils.getString(R.string.error201));
        } else {
            MyApplication.getApplication().showProgressDialog("", "正在登录中...", getActivity());
            mLoinPresenter.login(phone, pass);
        }
    }

    // 验证登陆
    private boolean chekLogin() {

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showToast(UIUtils.getString(R.string.error301));
            return false;
        }

        if (TextUtils.isEmpty(pass)) {
            ToastUtils.showToast(UIUtils.getString(R.string.error302));
            return false;
        }

        // 长度问题
        // 匹配正则
        if (phone.length() < 11) {
            // 不是手机号码
            ToastUtils.showToast(UIUtils.getString(R.string.error303));
            return false;
        }

        if (pass.length() < 6) {
            ToastUtils.showToast(UIUtils.getString(R.string.error304));
            return false;
        }

        // 匹配正则
        if (!StringUtils.matchPhone(phone)) {
            // 不是手机号码
            ToastUtils.showToast(UIUtils.getString(R.string.error305));
            return false;
        }

        return true;
    }


    @Override
    protected void setLoginrPhone(String phone) {
        etPhoneLogin.setText(phone);
        etPassLogin.setText("");
    }

    private void showUnRegisterDialog() {

        AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.setMessage("该手机号未注册");
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "去注册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 切换到注册页面,同时将手机号码也切换过去
                LoginActivity activity = (LoginActivity) mContext;
                activity.goToRegistView();
                // 向注册页面传递手机号码
                activity.getBaseFragment().setRegisterPhone(etPhoneLogin.getText().toString().trim());
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        Button posiviveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        posiviveButton.setTextColor(Color.parseColor("#F79444"));
        Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        negativeButton.setTextColor(Color.parseColor("#000000"));
    }

    @Override
    public void onSucceed() {

    }

    @Override
    public void onIsRegister(int data) {

    }

    @Override
    public void onLoginFailed(int errorCode) {
        hideProgress();

        switch (errorCode) {
            case Urls.CODE_Error_14:
                showUnRegisterDialog();
                break;
            case Urls.CODE_Error_15:
                ToastUtils.showToast("用户名或者密码错误");
                break;
            case Urls.CODE_Error_:
                ToastUtils.showToast("服务器连接失败!");
                break;
        }
    }

    @Override
    public void goToWelcomeAct() {
        hideProgress();
        ActivitySwitcher.goToWelcome2(getActivity());
        getActivity().finish();
    }

    @Override
    public void goToMainAct() {
        hideProgress();
        ActivitySwitcher.goMainActivity(getActivity());
        getActivity().finish();
    }

    private void hideProgress() {
        MyApplication.getApplication().hideProgressDialog();
    }
}
